/*
 * Project: Digital Wristwatch
 * Author: Zak Kemble, contact@zakkemble.co.uk
 * Copyright: (C) 2013 by Zak Kemble
 * License: GNU GPL v3 (see License.txt)
 * Web: http://blog.zakkemble.co.uk/diy-digital-wristwatch/
 */

#include <avr/io.h>
#include <avr/power.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <stdio.h>
#include "common.h"
#include "drivers/wdt.h"
#include "drivers/spi.h"
#include "drivers/uart.h"
#include "drivers/i2c.h"
#include "devices/oled.h"
#include "devices/PCF8563.h"
#include "devices/accelerate.h"
#include "devices/buttons.h"
#include "devices/battery.h"
#include "devices/buzzer.h"
#include "millis/millis.h"
#include "display.h"
#include "time.h"
#include "alarm.h"
#include "pwrmgr.h"
#include "watchface.h"
#include "watchfaces/normal.h"
#include "apps/stopwatch.h"
#include "watchconfig.h"

static void init(void);
#if WDT_ENABLE && WDT_DEBUG
static void resetError(void);
#else
#define resetError() ((void)(0))
#endif
//static void freeRAM(void);

int main(void)
{
	init();

	printf("\r\nHell Watch\r\n");

	buzzer_buzz(200, TONE_4KHZ, VOL_UI);
	watchface_setFace(watchface_normal);
	watchface_loadFace();
	battery_update();

	while(1)
	{
		bool timeUpt = time_update();
		if(pwrmgr_userActive())
		{
			if(timeUpt && timeData.secs == 0)
				battery_update();
			buttons_update();
		}
		buzzer_update();
		
		stopwatch_update();
		if(pwrmgr_userActive())
		{
			alarm_update();
			display_update();
		}
		
//		freeRAM();

		wdt_update();

		if(PCF8563_systemAlarmState()) {
			battery_log_update();
		}

		pwrmgr_update();
	}
}

static void init()
{
	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;

	// Everything else
	clock_init();
	millis_init();//Init first
	uart_init();
	spi_init();
	i2c_init();
	watchconfig_init();
	buzzer_init();
	battery_init();
	PCF8563_init();
	buttons_init();
	pwrmgr_init();
	time_init();
	alarm_init();
	oled_init();
	accel_init();
}
